package com.lkd.http.controller;
import com.lkd.common.VMSystem;
import com.lkd.entity.OrderEntity;
import com.lkd.service.OrderService;
import com.lkd.utils.ConvertUtils;
import com.lkd.vo.PayVO;
import com.lkd.wxpay.WXConfig;
import com.lkd.wxpay.WxPayDTO;
import com.lkd.wxpay.WxPaySDKUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private WxPaySDKUtil wxPaySDKUtil;


    //微信支付
    @PostMapping("/weixinPay")
    public  String weixinPay (@RequestBody PayVO payVO){
        var orderEntry = orderService.createOrder(payVO);
        //封装请求对象
        var wxPayDTO = new WxPayDTO();
        wxPayDTO.setBody(orderEntry.getSkuName());
        wxPayDTO.setOutTradeNo(orderEntry.getOrderNo());
        wxPayDTO.setTotalFee(orderEntry.getAmount());
        wxPayDTO.setOpenid(orderEntry.getOpenId());
        return wxPaySDKUtil.requestPay(wxPayDTO);
    }


    //订单微服务支付回调接口
    @RequestMapping("/payNotify")
    @ResponseBody
    public void payNotify(HttpServletRequest request, HttpServletResponse response){
        log.info("调用回调方法");
        try {
          /*  String notifyResult = ConvertUtils.convertToString(request.getInputStream());
            String ordersn = wxPaySDKUtil.validPay(notifyResult);*/
            String ordersn ="110";

            if (ordersn!=null){
                log.info("修改订单状态");
                OrderEntity orderEntity = orderService.getByOrderNo(ordersn);//查询订单
                if (orderEntity!=null){
                    orderEntity.setStatus(VMSystem.ORDER_STATUS_PAYED);//支付成功
                    orderEntity.setPayStatus(VMSystem.PAY_STATUS_PAYED);//支付成功
                    orderService.updateById(orderEntity);//保存
                     //发货
                    orderService.vendout(ordersn,orderEntity.getSkuId(),orderEntity.getInnerCode());
                    //成功响应
                    response.setContentType("text/xml");
                    response.getWriter().write(WXConfig.RESULT);
                }
            }
        }catch (Exception e){
            log.error("支付回调处处理失败");
        }
    }

}
